package com.example.linearlayoutdemo.avatar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class FileStorageHelper {
    private static final String TAG = "FileStorageHelper";
    private Context mContext;

    public FileStorageHelper(Context context) {
        this.mContext = context;
    }

    // 保存头像到本地存储
    public String saveAvatar(String userId, InputStream inputStream) {
        // 创建头像存储目录
        File avatarDir = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES), 
                                 Constants.AVATAR_DIR);
        if (!avatarDir.exists()) {
            if (!avatarDir.mkdirs()) {
                Log.e(TAG, "无法创建头像存储目录");
                return null;
            }
        }

        // 生成包含用户ID的唯一文件名，确保数据隔离
        String fileName = "avatar_" + userId + "_" + 
                         new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()) + ".jpg";
        File avatarFile = new File(avatarDir, fileName);

        try {
            // 读取输入流并保存到文件
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            FileOutputStream fos = new FileOutputStream(avatarFile);
            // 压缩保存为JPEG格式
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
            return avatarFile.getAbsolutePath();
        } catch (IOException e) {
            Log.e(TAG, "保存头像失败: " + e.getMessage());
            return null;
        }
    }

    // 获取头像文件的Bitmap
    public Bitmap getAvatar(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return null;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }

        // 解码文件为Bitmap
        return BitmapFactory.decodeFile(filePath);
    }

    // 删除旧头像
    public void deleteOldAvatar(String oldPath) {
        if (oldPath == null || oldPath.isEmpty()) {
            return;
        }

        File file = new File(oldPath);
        if (file.exists() && file.delete()) {
            Log.d(TAG, "旧头像已删除: " + oldPath);
        }
    }
}
